package com.javaee.term.aspect;

import com.javaee.term.constant.LoginCookieConstant;
import com.javaee.term.exception.SellerAuthorizeException;
import com.javaee.term.utils.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by aop实现登录检验
 * 2017-07-30 17:31
 */
@Aspect
@Component
@Slf4j
public class SellerAuthorizeAspect {

    @Pointcut("execution(public * com.javaee.term.controller.*.*(..))" +
    "&& !execution(public * com.javaee.term.controller.LoginController.*(..))")
    public void verify() {}

    @Before("verify()")
    public void doVerify() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        //查询cookie
        Cookie cookie = CookieUtil.get(request, LoginCookieConstant.TOKEN);
        if (cookie == null&& (!cookie.getValue().equals("token"))) {
            log.warn("【登录校验】Cookie中查不到token");
            throw new SellerAuthorizeException();
        }

    }
}
